﻿using Basic.UserCollect;
using Basic.UserLocalEvent;
using Basic.UserModel.LoginLog;
using Basic.UserModel.User;
using Basic.UserRemoteModel.User.Model;
using Basic.UserService.Interface;
using WeDonekRpc.Helper;

namespace Basic.UserService.Extend
{
    internal class WxLoginService : IWxLoginService
    {
        private readonly IUserCollect _User;
        private readonly IUserConfig _Config;
        private readonly ISaveLoginLog _LoginLog;

        public WxLoginService (IUserCollect user,
            IUserConfig config,
            ISaveLoginLog loginLog)
        {
            this._User = user;
            this._Config = config;
            this._LoginLog = loginLog;
        }

        public UserLoginResult WxLogin (WxLoginParam param)
        {
            long userId = this._User.GetUserId(param.LoginName, param.LoginType);
            return this._WxLogin(userId, param);
        }
        private UserLoginResult _WxLogin (long userId, WxLoginParam param)
        {
            param.Password = this._Config.CalculatePwd(param.Password);
            LoginLogAdd log = new LoginLogAdd
            {
                UserId = userId,
                LogSource = param.Source,
                LoginIp = param.LoginIp,
                LoginName = param.LoginName,
                LoginType = param.LoginType,
                LoginTime = DateTime.Now,
                ThirdAppId = param.ThirdAppId,
                ThirdUserId = param.WxUserId,
                UserAgent = param.UserAgent,
            };
            try
            {
                UserDatum user = this._User.UserLogin(userId, param.Password);
                if (param.IsBind)
                {
                    new WxUserBindEvent
                    {
                        UserId = userId,
                        WxUserId = param.WxUserId.Value
                    }.AsyncPublic();
                }
                log.LogShow = string.Format("用户({0})登陆成功,昵称:{1}。", param.LoginName, user.NickName);
                return new UserLoginResult
                {
                    UserId = userId,
                    Sex = user.Sex,
                    NickName = user.NickName,
                    UserHead = user.UserHead
                };
            }
            catch (ErrorException ex)
            {
                log.LogShow = string.Format("用户({0})登陆失败,错误码:{1}。", param.LoginName, ex.ErrorCode);
                throw;
            }
            finally
            {
                this._LoginLog.AddLog(log);
            }
        }
    }
}
